package com.classes;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.TreeMap;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;

import com.maxis.MaxisMPOS;
import com.mbbmap.app.manager.ConfigManager;
import com.mbbmap.app.manager.DBConnectionManager;

public class CombineMatchTraceInquiries {
	static String runDate = "";
	static String backDate = "";
	static String strOutDir = "";
	static String prefix = "";
	static String sequence_file = "";
	// date formatter
	static final SimpleDateFormat dateFormatter = new SimpleDateFormat("ddMMyyyy");
	static final SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMdd");
	// config declaration
	static final String CONFIG_FILE = "/match_trace.properties";
	static final java.util.Properties appCfg = new java.util.Properties();
	private static String CONFIG_LOG = "maxis-logging.properties";
	private static Log LOGGER;
	private static ArrayList<String> arrFileOut = new ArrayList<String>();

	/**
	 * Constructor
	 **/
	public CombineMatchTraceInquiries() {
		// Load the properties value
		try {
			InputStream stream = this.getClass().getResourceAsStream(CONFIG_FILE);
			if (stream != null)
				appCfg.load(stream);
			else
				throw new Exception("Input Stream is null");
		} catch (Exception e) {
			System.err.println("Error loading file " + CONFIG_FILE);
			System.err.println(e.getMessage());
			e.printStackTrace();
		}
		runDate = appCfg.getProperty("runDate");
		backDate = appCfg.getProperty("backDate");
		strOutDir = appCfg.getProperty("output_folder");
		prefix = appCfg.getProperty("file_name_prefix");
		sequence_file = appCfg.getProperty("sequence_file");
	}

	public static boolean writeMatchTrace(int merchant_id, int case_id, TreeMap<String, String> post, String user, String groupCode,
			String runNumber, Date date, String tran_ref_nbr) {
		Casemast c = CasemastFactory.getCaseMast(groupCode, case_id);
		if (c == null) {
			return false;
		}
		c.loadOutlets(case_id);
		ArrayList<CaseOutlet> c_outlets = c.getOutlets();
		SimpleDateFormat d = new SimpleDateFormat("yyyyMMdd");
		String headerType = "IDH";
		String mbr_id = "0002124";
		String strDate = d.format(date);
		String seq_nbr = String.format("%1$-2s", runNumber);
		String filler_0 = "";
		String filler_1 = "";
		String filler_2 = "";
		String tran_code = "651";
		String action = "I";
		String acn = "0002124";
		String rec_seg_num = "";
		String rec_type_1 = "1";
		String rec_type_2 = "2";
		String nbr_req_phntic_match = "3";
		String business_name = c.getMerchant().getRegisteredName();
		String dba = "";
		String street_addr_1 = "";
		String street_addr_2 = "";
		String city = "";
		String state = "";
		String zip = "";
		String country = "";
		String business_phone = "";
		String state_tax_nbr = "";
		String natl_tax_id = "";
		String trans_ref = "";
		String region_search_1 = "";
		String region_search_2 = "";
		String region_search_3 = "";
		String region_search_4 = "";
		String region_search_5 = "";
		String region_search_6 = "";
		String country_search_1 = "";
		String country_search_2 = "";
		String country_search_3 = "";
		String country_search_4 = "";
		String country_search_5 = "";
		String country_search_6 = "";
		String country_search_7 = "";
		String country_search_8 = "";
		String country_search_9 = "";
		String country_search_10 = "";
		String pr1_name_last = "";
		String pr1_name_first = "";
		String pr1_name_mid = "";
		String pr1_street_addr1 = "";
		String pr1_street_addr2 = "";
		String pr1_city = "";
		String pr1_state = "";
		String pr1_zip = "";
		String pr1_country = "";
		String pr1_phone = "";
		String pr1_natl_id = "";
		String pr1_license_id = "";
		String pr1_license_state = "";
		String pr1_license_country = "";
		String pr2_name_last = "";
		String pr2_name_first = "";
		String pr2_name_mid = "";
		String pr2_street_addr1 = "";
		String pr2_street_addr2 = "";
		String pr2_city = "";
		String pr2_state = "";
		String pr2_zip = "";
		String pr2_country = "";
		String pr2_phone = "";
		String pr2_natl_id = "";
		String pr2_license_id = "";
		String pr2_license_state = "";
		String pr2_license_country = "";
		String pr3_name_last = "";
		String pr3_name_first = "";
		String pr3_name_mid = "";
		String pr3_street_addr1 = "";
		String pr3_street_addr2 = "";
		String pr3_city = "";
		String pr3_state = "";
		String pr3_zip = "";
		String pr3_country = "";
		String pr3_phone = "";
		String pr3_natl_id = "";
		String pr3_license_id = "";
		String pr3_license_state = "";
		String pr3_license_country = "";
		String pr4_name_last = "";
		String pr4_name_first = "";
		String pr4_name_mid = "";
		String pr4_street_addr1 = "";
		String pr4_street_addr2 = "";
		String pr4_city = "";
		String pr4_state = "";
		String pr4_zip = "";
		String pr4_country = "";
		String pr4_phone = "";
		String pr4_natl_id = "";
		String pr4_license_id = "";
		String pr4_license_state = "";
		String pr4_license_country = "";
		String pr5_name_last = "";
		String pr5_name_first = "";
		String pr5_name_mid = "";
		String pr5_street_addr1 = "";
		String pr5_street_addr2 = "";
		String pr5_city = "";
		String pr5_state = "";
		String pr5_zip = "";
		String pr5_country = "";
		String pr5_phone = "";
		String pr5_natl_id = "";
		String pr5_license_id = "";
		String pr5_license_state = "";
		String pr5_license_country = "";
		String filler_6 = "";
		for (CaseOutlet c_outlet : c_outlets) {
			String line_1 = "";
			String line_2 = "";
			String postal_code = "";
			String line_city = "";
			JSONObject obj = (JSONObject) JSONValue.parse(c_outlet.getOutlet().getAddress());
			if (obj != null) {
				line_1 = (obj.get("line_1") == null) ? "" : obj.get("line_1").toString().trim();
				line_2 = (obj.get("line_2") == null) ? "" : obj.get("line_2").toString().trim();
				postal_code = (obj.get("postal_code") == null) ? "" : obj.get("postal_code").toString().trim();
				line_city = (obj.get("city") == null) ? "" : obj.get("city").toString().trim();
			}
			dba = c_outlet.getOutlet().getName();
			street_addr_1 = line_1;
			street_addr_2 = line_2;
			city = line_city;
			state = c.getCountryCode();
			if (state.indexOf("MXN") > -1 || state.indexOf("MXA") > -1) {
				state = "MY";
			}
			zip = postal_code;
			if (c.getCountryCode().equals("MY")) {
				country = "MYS";
			} else if (c.getCountryCode().equals("SG")) {
				country = "SGP";
			} else if (c.getCountryCode().equals("PH")) {
				country = "PHL";
			} else if (c.getCountryCode().equals("KH")) {
				country = "KHM";
			} else {
				country = c.getCountryCode();
			}
			business_phone = c_outlet.getOutlet().getCTTel();
			if ("000000000000000000".equals(business_phone)) {
				business_phone = "";
			}
			if(business_phone.length() > 10){
				business_phone = business_phone.substring(business_phone.length() - 10, business_phone.length());
			}
			break;
		}
		try {
			// String fileName = strOutDir + prefix + "_" + dateFormatter.format(date) + "_" + country + "_" + runNumber + ".txt";
			String fileName = strOutDir + prefix + "_" + dateFormatter.format(date) + "_" + runNumber + ".txt";
			if (!arrFileOut.contains(fileName)) {
				arrFileOut.add(fileName);
			}
			File f = new File(fileName);
			if (f.exists()) {
				BufferedReader br = new BufferedReader(new FileReader(f));
				int line = 0;
				while (br.readLine() != null) {
					line++;
				}
				br.close();
				String type1Line = "";
				String type2Line = "";
				FileWriter fw = new FileWriter(f, true);
				// write Header
				// headerType = String.format("%1$-3s", headerType);
				tran_code = String.format("%1$-3s", tran_code.trim());
				acn = String.format("%1$-7s", acn.trim());
				// mbr_id = String.format("%1$-7s", mbr_id);
				// strDate = String.format("%1$-7s", strDate);
				// filler_0 = String.format("%1$-982s", filler_0);
				// Write type 1 line
				action = String.format("%1$-1s", action.trim());
				rec_seg_num = String.format("%06d", line);
				rec_type_1 = String.format("%1$-1s", rec_type_1);
				nbr_req_phntic_match = String.format("%1$-1s", nbr_req_phntic_match);
				business_name = String.format("%1$-30s", business_name.trim());
				dba = String.format("%1$-30s", dba.trim());
				street_addr_1 = String.format("%1$-30s", street_addr_1.trim());
				street_addr_2 = String.format("%1$-30s", street_addr_2.trim());
				city = String.format("%1$-15s", city.trim());
				state = String.format("%1$-2s", state.trim());
				zip = String.format("%1$-10s", zip.trim());
				country = String.format("%1$-3s", country.trim());
				business_phone = String.format("%1$-10s", business_phone.trim());
				state_tax_nbr = String.format("%1$-9s", state_tax_nbr.trim());
				natl_tax_id = String.format("%1$-9s", natl_tax_id.trim());
				trans_ref = String.format("%1$-5s", tran_ref_nbr.trim());
				region_search_1 = String.format("%1$-3s", region_search_1.trim());
				region_search_2 = String.format("%1$-3s", region_search_2.trim());
				region_search_3 = String.format("%1$-3s", region_search_3.trim());
				region_search_4 = String.format("%1$-3s", region_search_4.trim());
				region_search_5 = String.format("%1$-3s", region_search_5.trim());
				region_search_6 = String.format("%1$-3s", region_search_6.trim());
				country_search_1 = String.format("%1$-3s", country_search_1.trim());
				country_search_2 = String.format("%1$-3s", country_search_2.trim());
				country_search_3 = String.format("%1$-3s", country_search_3.trim());
				country_search_4 = String.format("%1$-3s", country_search_4.trim());
				country_search_5 = String.format("%1$-3s", country_search_5.trim());
				country_search_6 = String.format("%1$-3s", country_search_6.trim());
				country_search_7 = String.format("%1$-3s", country_search_7.trim());
				country_search_8 = String.format("%1$-3s", country_search_8.trim());
				country_search_9 = String.format("%1$-3s", country_search_9.trim());
				country_search_10 = String.format("%1$-3s", country_search_10.trim());
				filler_1 = String.format("%1$-762s", filler_1);
				type1Line = tran_code + action + acn + rec_seg_num + rec_type_1 + nbr_req_phntic_match + business_name + dba + street_addr_1
						+ street_addr_2 + city + state + zip + country + business_phone + state_tax_nbr + natl_tax_id + trans_ref + region_search_1
						+ region_search_2 + region_search_3 + region_search_4 + region_search_5 + region_search_6 + country_search_1
						+ country_search_2 + country_search_3 + country_search_4 + country_search_5 + country_search_6 + country_search_7
						+ country_search_8 + country_search_9 + country_search_10 + filler_1;
				fw.write(type1Line + "\r\n");
				// write type 2 line
				String match_trace = c.getMerchant().getMatchTrace();
				JSONArray arr = (JSONArray) JSONValue.parse(match_trace);
				int k = 0;
				if(arr != null){
					while (k < arr.size()) {
						k++;
						int n = k - 1;
						// System.out.println("***" + n);
						String string = arr.get(n).toString();
						JSONObject obj = (JSONObject) JSONValue.parse(string);
						String f_name = (obj.get("f_name") == null) ? "" : obj.get("f_name").toString().trim();
						String l_name = (obj.get("l_name") == null) ? "" : obj.get("l_name").toString().trim();
						String ic = (obj.get("ic") == null) ? "" : obj.get("ic").toString().trim();
						String country_code = (obj.get("country_code") == null) ? "" : obj.get("country_code").toString().trim();
						int mod_5 = k % 5;
						switch (mod_5) {
						case 1:
							pr1_name_last = l_name;
							pr1_name_first = f_name;
							pr1_country = country_code;
							pr1_license_country = country_code;
							if (country_code.equals("MYS")) {
								pr1_natl_id = "";
								pr1_license_id = ic;
							} else {
								pr1_natl_id = ic;
								pr1_license_id = "";
							}
							break;
						case 2:
							pr2_name_last = l_name;
							pr2_name_first = f_name;
							pr2_country = country_code;
							pr2_license_country = country_code;
							if (country_code.equals("MYS")) {
								pr2_natl_id = "";
								pr2_license_id = ic;
							} else {
								pr2_natl_id = ic;
								pr2_license_id = "";
							}
							break;
						case 3:
							pr3_name_last = l_name;
							pr3_name_first = f_name;
							pr3_country = country_code;
							pr3_license_country = country_code;
							if (country_code.equals("MYS")) {
								pr3_natl_id = "";
								pr3_license_id = ic;
							} else {
								pr3_natl_id = ic;
								pr3_license_id = "";
							}
							break;
						case 4:
							pr4_name_last = l_name;
							pr4_name_first = f_name;
							pr4_country = country_code;
							pr4_license_country = country_code;
							if (country_code.equals("MYS")) {
								pr4_natl_id = "";
								pr4_license_id = ic;
							} else {
								pr4_natl_id = ic;
								pr4_license_id = "";
							}
							break;
						case 0:
							pr5_name_last = l_name;
							pr5_name_first = f_name;
							pr5_country = country_code;
							pr5_license_country = country_code;
							if (country_code.equals("MYS")) {
								pr5_natl_id = "";
								pr5_license_id = ic;
							} else {
								pr5_natl_id = ic;
								pr5_license_id = "";
							}
							break;
						default:
							break;
						}
					}
				}
				line++;
				rec_seg_num = String.format("%06d", line);
				rec_type_2 = String.format("%1$-1s", rec_type_2);
				pr1_name_last = String.format("%1$-25s", pr1_name_last.trim());
				pr1_name_first = String.format("%1$-15s", pr1_name_first.trim());
				pr1_name_mid = String.format("%1$-1s", pr1_name_mid.trim());
				pr1_street_addr1 = String.format("%1$-30s", pr1_street_addr1.trim());
				pr1_street_addr2 = String.format("%1$-30s", pr1_street_addr2.trim());
				pr1_city = String.format("%1$-15s", pr1_city.trim());
				pr1_state = String.format("%1$-2s", pr1_state.trim());
				pr1_zip = String.format("%1$-10s", pr1_zip.trim());
				pr1_country = String.format("%1$-3s", pr1_country.trim());
				pr1_phone = String.format("%1$-10s", pr1_phone.trim());
				pr1_natl_id = String.format("%1$-9s", pr1_natl_id.trim());
				pr1_license_id = String.format("%1$-25s", pr1_license_id.trim());
				pr1_license_state = String.format("%1$-2s", pr1_license_state.trim());
				pr1_license_country = String.format("%1$-3s", pr1_license_country.trim());
				pr2_name_last = String.format("%1$-25s", pr2_name_last.trim());
				pr2_name_first = String.format("%1$-15s", pr2_name_first.trim());
				pr2_name_mid = String.format("%1$-1s", pr2_name_mid.trim());
				pr2_street_addr1 = String.format("%1$-30s", pr2_street_addr1.trim());
				pr2_street_addr2 = String.format("%1$-30s", pr2_street_addr2.trim());
				pr2_city = String.format("%1$-15s", pr2_city.trim());
				pr2_state = String.format("%1$-2s", pr2_state.trim());
				pr2_zip = String.format("%1$-10s", pr2_zip.trim());
				pr2_country = String.format("%1$-3s", pr2_country.trim());
				pr2_phone = String.format("%1$-10s", pr2_phone.trim());
				pr2_natl_id = String.format("%1$-9s", pr2_natl_id.trim());
				pr2_license_id = String.format("%1$-25s", pr2_license_id.trim());
				pr2_license_state = String.format("%1$-2s", pr2_license_state.trim());
				pr2_license_country = String.format("%1$-3s", pr2_license_country.trim());
				pr3_name_last = String.format("%1$-25s", pr3_name_last.trim());
				pr3_name_first = String.format("%1$-15s", pr3_name_first.trim());
				pr3_name_mid = String.format("%1$-1s", pr3_name_mid.trim());
				pr3_street_addr1 = String.format("%1$-30s", pr3_street_addr1.trim());
				pr3_street_addr2 = String.format("%1$-30s", pr3_street_addr2.trim());
				pr3_city = String.format("%1$-15s", pr3_city.trim());
				pr3_state = String.format("%1$-2s", pr3_state.trim());
				pr3_zip = String.format("%1$-10s", pr3_zip.trim());
				pr3_country = String.format("%1$-3s", pr3_country.trim());
				pr3_phone = String.format("%1$-10s", pr3_phone.trim());
				pr3_natl_id = String.format("%1$-9s", pr3_natl_id.trim());
				pr3_license_id = String.format("%1$-25s", pr3_license_id.trim());
				pr3_license_state = String.format("%1$-2s", pr3_license_state.trim());
				pr3_license_country = String.format("%1$-3s", pr3_license_country.trim());
				pr4_name_last = String.format("%1$-25s", pr4_name_last.trim());
				pr4_name_first = String.format("%1$-15s", pr4_name_first.trim());
				pr4_name_mid = String.format("%1$-1s", pr4_name_mid.trim());
				pr4_street_addr1 = String.format("%1$-30s", pr4_street_addr1.trim());
				pr4_street_addr2 = String.format("%1$-30s", pr4_street_addr2.trim());
				pr4_city = String.format("%1$-15s", pr4_city.trim());
				pr4_state = String.format("%1$-2s", pr4_state.trim());
				pr4_zip = String.format("%1$-10s", pr4_zip.trim());
				pr4_country = String.format("%1$-3s", pr4_country.trim());
				pr4_phone = String.format("%1$-10s", pr4_phone.trim());
				pr4_natl_id = String.format("%1$-9s", pr4_natl_id.trim());
				pr4_license_id = String.format("%1$-25s", pr4_license_id.trim());
				pr4_license_state = String.format("%1$-2s", pr4_license_state.trim());
				pr4_license_country = String.format("%1$-3s", pr4_license_country.trim());
				pr5_name_last = String.format("%1$-25s", pr5_name_last.trim());
				pr5_name_first = String.format("%1$-15s", pr5_name_first.trim());
				pr5_name_mid = String.format("%1$-1s", pr5_name_mid.trim());
				pr5_street_addr1 = String.format("%1$-30s", pr5_street_addr1.trim());
				pr5_street_addr2 = String.format("%1$-30s", pr5_street_addr2.trim());
				pr5_city = String.format("%1$-15s", pr5_city.trim());
				pr5_state = String.format("%1$-2s", pr5_state.trim());
				pr5_zip = String.format("%1$-10s", pr5_zip.trim());
				pr5_country = String.format("%1$-3s", pr5_country.trim());
				pr5_phone = String.format("%1$-10s", pr5_phone.trim());
				pr5_natl_id = String.format("%1$-9s", pr5_natl_id.trim());
				pr5_license_id = String.format("%1$-25s", pr5_license_id.trim());
				pr5_license_state = String.format("%1$-2s", pr5_license_state.trim());
				pr5_license_country = String.format("%1$-3s", pr5_license_country.trim());
				filler_2 = String.format("%1$-94s", filler_6.trim());
				type2Line = tran_code + action + acn + rec_seg_num + rec_type_2 + pr1_name_last + pr1_name_first + pr1_name_mid + pr1_street_addr1
						+ pr1_street_addr2 + pr1_city + pr1_state + pr1_zip + pr1_country + pr1_phone + pr1_natl_id + pr1_license_id
						+ pr1_license_state + pr1_license_country + pr2_name_last + pr2_name_first + pr2_name_mid + pr2_street_addr1
						+ pr2_street_addr2 + pr2_city + pr2_state + pr2_zip + pr2_country + pr2_phone + pr2_natl_id + pr2_license_id
						+ pr2_license_state + pr2_license_country + pr3_name_last + pr3_name_first + pr3_name_mid + pr3_street_addr1
						+ pr3_street_addr2 + pr3_city + pr3_state + pr3_zip + pr3_country + pr3_phone + pr3_natl_id + pr3_license_id
						+ pr3_license_state + pr3_license_country + pr4_name_last + pr4_name_first + pr4_name_mid + pr4_street_addr1
						+ pr4_street_addr2 + pr4_city + pr4_state + pr4_zip + pr4_country + pr4_phone + pr4_natl_id + pr4_license_id
						+ pr4_license_state + pr4_license_country + pr5_name_last + pr5_name_first + pr5_name_mid + pr5_street_addr1
						+ pr5_street_addr2 + pr5_city + pr5_state + pr5_zip + pr5_country + pr5_phone + pr5_natl_id + pr5_license_id
						+ pr5_license_state + pr5_license_country + filler_2;
				fw.write(type2Line + "\r\n");
				fw.close();
			} else {
				f.createNewFile();
				int currentLine = 1;
				String type1Line = "";
				String type2Line = "";
				String headerLine = "";
				FileWriter fw = new FileWriter(f);
				// write Header
				headerType = String.format("%1$-3s", headerType);
				tran_code = String.format("%1$-3s", tran_code.trim());
				acn = String.format("%1$-7s", acn.trim());
				mbr_id = String.format("%1$-7s", mbr_id);
				strDate = String.format("%1$-7s", strDate);
				filler_0 = String.format("%1$-982s", filler_0);
				headerLine = headerType + tran_code + acn + mbr_id + strDate + seq_nbr + filler_0;
				fw.write(headerLine + "\r\n");
				// Write type 1 line
				action = String.format("%1$-1s", action.trim());
				rec_seg_num = String.format("%06d", currentLine);
				rec_type_1 = String.format("%1$-1s", rec_type_1);
				nbr_req_phntic_match = String.format("%1$-1s", nbr_req_phntic_match);
				business_name = String.format("%1$-30s", business_name.trim());
				dba = String.format("%1$-30s", dba.trim());
				street_addr_1 = String.format("%1$-30s", street_addr_1.trim());
				street_addr_2 = String.format("%1$-30s", street_addr_2.trim());
				city = String.format("%1$-15s", city.trim());
				state = String.format("%1$-2s", state.trim());
				zip = String.format("%1$-10s", zip.trim());
				country = String.format("%1$-3s", country.trim());
				business_phone = String.format("%1$-10s", business_phone.trim());
				state_tax_nbr = String.format("%1$-9s", state_tax_nbr.trim());
				natl_tax_id = String.format("%1$-9s", natl_tax_id.trim());
				trans_ref = String.format("%1$-5s", tran_ref_nbr.trim());
				region_search_1 = String.format("%1$-3s", region_search_1.trim());
				region_search_2 = String.format("%1$-3s", region_search_2.trim());
				region_search_3 = String.format("%1$-3s", region_search_3.trim());
				region_search_4 = String.format("%1$-3s", region_search_4.trim());
				region_search_5 = String.format("%1$-3s", region_search_5.trim());
				region_search_6 = String.format("%1$-3s", region_search_6.trim());
				country_search_1 = String.format("%1$-3s", country_search_1.trim());
				country_search_2 = String.format("%1$-3s", country_search_2.trim());
				country_search_3 = String.format("%1$-3s", country_search_3.trim());
				country_search_4 = String.format("%1$-3s", country_search_4.trim());
				country_search_5 = String.format("%1$-3s", country_search_5.trim());
				country_search_6 = String.format("%1$-3s", country_search_6.trim());
				country_search_7 = String.format("%1$-3s", country_search_7.trim());
				country_search_8 = String.format("%1$-3s", country_search_8.trim());
				country_search_9 = String.format("%1$-3s", country_search_9.trim());
				country_search_10 = String.format("%1$-3s", country_search_10.trim());
				filler_1 = String.format("%1$-762s", filler_1);
				type1Line = tran_code + action + acn + rec_seg_num + rec_type_1 + nbr_req_phntic_match + business_name + dba + street_addr_1
						+ street_addr_2 + city + state + zip + country + business_phone + state_tax_nbr + natl_tax_id + trans_ref + region_search_1
						+ region_search_2 + region_search_3 + region_search_4 + region_search_5 + region_search_6 + country_search_1
						+ country_search_2 + country_search_3 + country_search_4 + country_search_5 + country_search_6 + country_search_7
						+ country_search_8 + country_search_9 + country_search_10 + filler_1;
				fw.write(type1Line + "\r\n");
				// write type 2 line
				String match_trace = c.getMerchant().getMatchTrace();
				JSONArray arr = (JSONArray) JSONValue.parse(match_trace);
				int k = 0;
				if(arr != null){
					while (k < arr.size()) {
						k++;
						int n = k - 1;
						System.out.println("***" + n);
						String string = arr.get(n).toString();
						JSONObject obj = (JSONObject) JSONValue.parse(string);
						String f_name = (obj.get("f_name") == null) ? "" : obj.get("f_name").toString().trim();
						String l_name = (obj.get("l_name") == null) ? "" : obj.get("l_name").toString().trim();
						String ic = (obj.get("ic") == null) ? "" : obj.get("ic").toString().trim();
						String country_code = (obj.get("country_code") == null) ? "" : obj.get("country_code").toString().trim();
						int mod_5 = k % 5;
						switch (mod_5) {
						case 1:
							pr1_name_last = l_name;
							pr1_name_first = f_name;
							pr1_country = country_code;
							pr1_license_country = country_code;
							if (country_code.equals("MYS")) {
								pr1_natl_id = "";
								pr1_license_id = ic;
							} else {
								pr1_natl_id = ic;
								pr1_license_id = "";
							}
							break;
						case 2:
							pr2_name_last = l_name;
							pr2_name_first = f_name;
							pr2_country = country_code;
							pr2_license_country = country_code;
							if (country_code.equals("MYS")) {
								pr2_natl_id = "";
								pr2_license_id = ic;
							} else {
								pr2_natl_id = ic;
								pr2_license_id = "";
							}
							break;
						case 3:
							pr3_name_last = l_name;
							pr3_name_first = f_name;
							pr3_country = country_code;
							pr3_license_country = country_code;
							if (country_code.equals("MYS")) {
								pr3_natl_id = "";
								pr3_license_id = ic;
							} else {
								pr3_natl_id = ic;
								pr3_license_id = "";
							}
							break;
						case 4:
							pr4_name_last = l_name;
							pr4_name_first = f_name;
							pr4_country = country_code;
							pr4_license_country = country_code;
							if (country_code.equals("MYS")) {
								pr4_natl_id = "";
								pr4_license_id = ic;
							} else {
								pr4_natl_id = ic;
								pr4_license_id = "";
							}
							break;
						case 0:
							pr5_name_last = l_name;
							pr5_name_first = f_name;
							pr5_country = country_code;
							pr5_license_country = country_code;
							if (country_code.equals("MYS")) {
								pr5_natl_id = "";
								pr5_license_id = ic;
							} else {
								pr5_natl_id = ic;
								pr5_license_id = "";
							}
							break;
						default:
							break;
						}
					}
			}
				currentLine++;
				rec_seg_num = String.format("%06d", currentLine);
				rec_type_2 = String.format("%1$-1s", rec_type_2);
				pr1_name_last = String.format("%1$-25s", pr1_name_last.trim());
				pr1_name_first = String.format("%1$-15s", pr1_name_first.trim());
				pr1_name_mid = String.format("%1$-1s", pr1_name_mid.trim());
				pr1_street_addr1 = String.format("%1$-30s", pr1_street_addr1.trim());
				pr1_street_addr2 = String.format("%1$-30s", pr1_street_addr2.trim());
				pr1_city = String.format("%1$-15s", pr1_city.trim());
				pr1_state = String.format("%1$-2s", pr1_state.trim());
				pr1_zip = String.format("%1$-10s", pr1_zip.trim());
				pr1_country = String.format("%1$-3s", pr1_country.trim());
				pr1_phone = String.format("%1$-10s", pr1_phone.trim());
				pr1_natl_id = String.format("%1$-9s", pr1_natl_id.trim());
				pr1_license_id = String.format("%1$-25s", pr1_license_id.trim());
				pr1_license_state = String.format("%1$-2s", pr1_license_state.trim());
				pr1_license_country = String.format("%1$-3s", pr1_license_country.trim());
				pr2_name_last = String.format("%1$-25s", pr2_name_last.trim());
				pr2_name_first = String.format("%1$-15s", pr2_name_first.trim());
				pr2_name_mid = String.format("%1$-1s", pr2_name_mid.trim());
				pr2_street_addr1 = String.format("%1$-30s", pr2_street_addr1.trim());
				pr2_street_addr2 = String.format("%1$-30s", pr2_street_addr2.trim());
				pr2_city = String.format("%1$-15s", pr2_city.trim());
				pr2_state = String.format("%1$-2s", pr2_state.trim());
				pr2_zip = String.format("%1$-10s", pr2_zip.trim());
				pr2_country = String.format("%1$-3s", pr2_country.trim());
				pr2_phone = String.format("%1$-10s", pr2_phone.trim());
				pr2_natl_id = String.format("%1$-9s", pr2_natl_id.trim());
				pr2_license_id = String.format("%1$-25s", pr2_license_id.trim());
				pr2_license_state = String.format("%1$-2s", pr2_license_state.trim());
				pr2_license_country = String.format("%1$-3s", pr2_license_country.trim());
				pr3_name_last = String.format("%1$-25s", pr3_name_last.trim());
				pr3_name_first = String.format("%1$-15s", pr3_name_first.trim());
				pr3_name_mid = String.format("%1$-1s", pr3_name_mid.trim());
				pr3_street_addr1 = String.format("%1$-30s", pr3_street_addr1.trim());
				pr3_street_addr2 = String.format("%1$-30s", pr3_street_addr2.trim());
				pr3_city = String.format("%1$-15s", pr3_city.trim());
				pr3_state = String.format("%1$-2s", pr3_state.trim());
				pr3_zip = String.format("%1$-10s", pr3_zip.trim());
				pr3_country = String.format("%1$-3s", pr3_country.trim());
				pr3_phone = String.format("%1$-10s", pr3_phone.trim());
				pr3_natl_id = String.format("%1$-9s", pr3_natl_id.trim());
				pr3_license_id = String.format("%1$-25s", pr3_license_id.trim());
				pr3_license_state = String.format("%1$-2s", pr3_license_state.trim());
				pr3_license_country = String.format("%1$-3s", pr3_license_country.trim());
				pr4_name_last = String.format("%1$-25s", pr4_name_last.trim());
				pr4_name_first = String.format("%1$-15s", pr4_name_first.trim());
				pr4_name_mid = String.format("%1$-1s", pr4_name_mid.trim());
				pr4_street_addr1 = String.format("%1$-30s", pr4_street_addr1.trim());
				pr4_street_addr2 = String.format("%1$-30s", pr4_street_addr2.trim());
				pr4_city = String.format("%1$-15s", pr4_city.trim());
				pr4_state = String.format("%1$-2s", pr4_state.trim());
				pr4_zip = String.format("%1$-10s", pr4_zip.trim());
				pr4_country = String.format("%1$-3s", pr4_country.trim());
				pr4_phone = String.format("%1$-10s", pr4_phone.trim());
				pr4_natl_id = String.format("%1$-9s", pr4_natl_id.trim());
				pr4_license_id = String.format("%1$-25s", pr4_license_id.trim());
				pr4_license_state = String.format("%1$-2s", pr4_license_state.trim());
				pr4_license_country = String.format("%1$-3s", pr4_license_country.trim());
				pr5_name_last = String.format("%1$-25s", pr5_name_last.trim());
				pr5_name_first = String.format("%1$-15s", pr5_name_first.trim());
				pr5_name_mid = String.format("%1$-1s", pr5_name_mid.trim());
				pr5_street_addr1 = String.format("%1$-30s", pr5_street_addr1.trim());
				pr5_street_addr2 = String.format("%1$-30s", pr5_street_addr2.trim());
				pr5_city = String.format("%1$-15s", pr5_city.trim());
				pr5_state = String.format("%1$-2s", pr5_state.trim());
				pr5_zip = String.format("%1$-10s", pr5_zip.trim());
				pr5_country = String.format("%1$-3s", pr5_country.trim());
				pr5_phone = String.format("%1$-10s", pr5_phone.trim());
				pr5_natl_id = String.format("%1$-9s", pr5_natl_id.trim());
				pr5_license_id = String.format("%1$-25s", pr5_license_id.trim());
				pr5_license_state = String.format("%1$-2s", pr5_license_state.trim());
				pr5_license_country = String.format("%1$-3s", pr5_license_country.trim());
				filler_2 = String.format("%1$-94s", filler_6.trim());
				type2Line = tran_code + action + acn + rec_seg_num + rec_type_2 + pr1_name_last + pr1_name_first + pr1_name_mid + pr1_street_addr1
						+ pr1_street_addr2 + pr1_city + pr1_state + pr1_zip + pr1_country + pr1_phone + pr1_natl_id + pr1_license_id
						+ pr1_license_state + pr1_license_country + pr2_name_last + pr2_name_first + pr2_name_mid + pr2_street_addr1
						+ pr2_street_addr2 + pr2_city + pr2_state + pr2_zip + pr2_country + pr2_phone + pr2_natl_id + pr2_license_id
						+ pr2_license_state + pr2_license_country + pr3_name_last + pr3_name_first + pr3_name_mid + pr3_street_addr1
						+ pr3_street_addr2 + pr3_city + pr3_state + pr3_zip + pr3_country + pr3_phone + pr3_natl_id + pr3_license_id
						+ pr3_license_state + pr3_license_country + pr4_name_last + pr4_name_first + pr4_name_mid + pr4_street_addr1
						+ pr4_street_addr2 + pr4_city + pr4_state + pr4_zip + pr4_country + pr4_phone + pr4_natl_id + pr4_license_id
						+ pr4_license_state + pr4_license_country + pr5_name_last + pr5_name_first + pr5_name_mid + pr5_street_addr1
						+ pr5_street_addr2 + pr5_city + pr5_state + pr5_zip + pr5_country + pr5_phone + pr5_natl_id + pr5_license_id
						+ pr5_license_state + pr5_license_country + filler_2;
				fw.write(type2Line + "\r\n");
				fw.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return true;
	}

	public ArrayList<Casemast> getUnprocessedCaseMast(Date runDate) {
        String connectionPool = ConfigManager.getInstance().getConnectionPool();
        DBConnectionManager connMgr = DBConnectionManager.getInstance();
        Connection conn = connMgr.getConnection(connectionPool, 10000);

		ArrayList<Casemast> cArr = new ArrayList<Casemast>();

				try {
					String sql = "select casemast.*, role_name from casemast " + "left join tblaccessrole on c_group_code = role_code "
//							+ "left join tbltree on child_id = c_group_code "
							+ "where to_char(C_MODIFIED_DATE,'YYYYMMDD') = ? and C_STATUS_MATCH_TRACE = '00' " + "order by c_id desc";
					PreparedStatement pstmt = conn.prepareStatement(sql);
					String strDate = sdf1.format(runDate);
					pstmt.setString(1, strDate);
					ResultSet rs = pstmt.executeQuery();
					try {
						while (rs.next()) {
							Casemast c = CasemastFactory.parseResultSet(rs);
							cArr.add(c);
						}
					} finally {
						rs.close();
						pstmt.close();
					}
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					connMgr.freeConnection(connectionPool, conn);
				}


		return cArr;
	}

	public void updateStatusMatchTrace(ArrayList<Casemast> cArr) {
        String connectionPool = ConfigManager.getInstance().getConnectionPool();
        DBConnectionManager connMgr = DBConnectionManager.getInstance();
        Connection conn = connMgr.getConnection(connectionPool, 10000);
		
			try {
				String sql = "UPDATE CASEMAST SET C_STATUS_MATCH_TRACE = '01' WHERE C_ID = ?";
				PreparedStatement pstmt = conn.prepareStatement(sql);
				for (Casemast c : cArr) {
					pstmt.setLong(1, c.getId());
					pstmt.addBatch();
				}
				pstmt.executeBatch();
				pstmt.close();
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				connMgr.freeConnection(connectionPool, conn);
			}
	}

	private String getRunTimeValue(Date date) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		String todayDate = dateFormatter.format(cal.getTime());
		cal.add(Calendar.DATE, -1);
		String oldDate = dateFormatter.format(cal.getTime());
		File oldFile = new File(strOutDir + File.separator + "temp" + File.separator + oldDate + ".txt");
		File newFile = new File(strOutDir + File.separator + "temp" + File.separator + todayDate + ".txt");
		if (oldFile.exists()) {
			System.out.println("Delete yesterday file successful : " + oldFile.delete());
		}
		int runNumber = 0;
		if (newFile.exists()) {
			try {
				BufferedReader br = new BufferedReader(new FileReader(newFile));
				String temp = "";
				while ((temp = br.readLine()) != null) {
					if (StringUtils.isNotBlank(temp)) {
						runNumber = Integer.parseInt(temp.trim());
					}
				}
				runNumber++;
				br.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			try {
				newFile.createNewFile();
				runNumber = 1;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		try {
			FileWriter fw = new FileWriter(newFile);
			fw.write(runNumber + "\r\n");
			fw.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return runNumber < 10 ? "0" + runNumber : runNumber + "";
	}

	public static void main(String[] args) {
		String configPropertyFilePath = MaxisMPOS.class.getClassLoader().getResource(CONFIG_LOG).toString().substring("file:/".length());
		System.setProperty("java.util.logging.config.file", configPropertyFilePath);
		LOGGER = LogFactory.getLog(CombineMatchTraceInquiries.class);
		CombineMatchTraceInquiries c = new CombineMatchTraceInquiries();
		Date date = new Date();
		if (StringUtils.isNotBlank(runDate)) {
			try {
				date = dateFormatter.parse(runDate);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if (StringUtils.isNotBlank(backDate)){
			Calendar cal = Calendar.getInstance();
			cal.setTime(date);
			int amount = 0;
			try {
				amount = Integer.parseInt(backDate);
			} catch (Exception e){
				e.printStackTrace();
			}
			cal.add(Calendar.DATE, amount);
			date = cal.getTime();
		}
		String strRunTime = c.getRunTimeValue(date);
		ArrayList<Casemast> cArr = c.getUnprocessedCaseMast(date);
		int tran_ref_nbr = c.getLastSequenceNbr();
		if (cArr.size() > 0) {
			for (Casemast item : cArr) {
				if (tran_ref_nbr == 10000) {
					tran_ref_nbr = 1;
				}
				int merchant_id = (int) item.getMerchant().getId();
				int case_id = (int) item.getId();
				TreeMap<String, String> post = new TreeMap<String, String>();
				post.put("app_type", item.getType());
				post.put("ownership_status", item.getMerchant().getOwnershipStatus());
				post.put("match_trace", item.getMerchant().getMatchTrace());
				System.out.println("Processing Tran_ref_nbr : " + "1" + String.format("%04d", tran_ref_nbr));
				writeMatchTrace(merchant_id, case_id, post, item.getCreatedBy(), item.getGroupCode(), strRunTime, date,
						"1" + String.format("%04d", tran_ref_nbr));
				tran_ref_nbr++;
			}
		} else {
			System.out.println("Casemast not found!");
		}
		System.out.println("--------DONE--------");
		c.writeFooter(strRunTime, date);
		c.writeSequenceFile(tran_ref_nbr);
		c.updateStatusMatchTrace(cArr);
	}

	private int getLastSequenceNbr() {
		int number = 1;
		try {
			File file = new File(sequence_file);
			if (file.exists()) {
				BufferedReader br = new BufferedReader(new FileReader(file));
				String temp = "";
				while ((temp = br.readLine()) != null) {
					if (StringUtils.isNotBlank(temp.trim())) {
						number = Integer.parseInt(temp);
					}
				}
				br.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return number;
	}

	private void writeSequenceFile(int num) {
		try {
			File file = new File(sequence_file);
			file.createNewFile();
			FileWriter fw = new FileWriter(file);
			fw.write(num + "");
			fw.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void writeFooter(String seqNum, Date date) {
		String type = "IDT";
		String tran_code = "651";
		String acn = "0002124";
		String mbr_id = "0002124";
		String strDate = String.format("%1$-8s", sdf1.format(date));
		String seq_nbr = String.format("%1$-2s", seqNum);
		String tot_a_rec = "0000000000";
		String tot_i_rec = "";
		String tot_rec = "";
		String filler = "";
		String footerLine = "";
		for (String fileName : arrFileOut) {
			File f = new File(fileName);
			try {
				BufferedReader br = new BufferedReader(new FileReader(f));
				int line = 0;
				String temp = "";
				while ((temp = br.readLine()) != null) {
					if (StringUtils.isNotBlank(temp)) {
						line++;
					}
				}
				br.close();
				int totalApp = line / 2;
				type = String.format("%1$-3s", type);
				tran_code = String.format("%1$-3s", tran_code);
				acn = String.format("%1$-7s", acn);
				mbr_id = String.format("%1$-7s", mbr_id);
				tot_a_rec = String.format("%1$-10s", tot_a_rec);
				tot_i_rec = String.format("%010d", totalApp);
				tot_rec = String.format("%010d", totalApp);
				filler = String.format("%1$-952s", filler);
				footerLine = type + tran_code + acn + mbr_id + strDate + seq_nbr + tot_a_rec + tot_i_rec + tot_rec + filler;
				FileWriter fw = new FileWriter(f, true);
				fw.write(footerLine);
				fw.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
